<template>
    <div style="">
        <component v-for="dlg in dlgs" :is="dlg.formName" @close="doClose(dlg)" v-bind="dlg.props" v-bind:key="dlg.key"
            :ref="'dlg' + dlg.key"></component>
    </div>
</template>

<script>
import { nextTick, resolveComponent, toRaw } from 'vue';
export default {
    name: "MyDlgManager",
    data() {
        return {
            dlgs: [],
        }
    },
    methods: {
        close() {
            //关闭当前最上面的dlg
            if (this.dlgs.length > 0) {
                let dlg = this.dlgs.pop();
            }
        },
        makeDlg(key, formName, props) {
            return new Promise(async (resolve, reject) => {
                await $server.loadComponent(formName);
                let dlg = this.dlgs.filter(p => p.key == key)[0];
                if (!dlg) {
                    dlg = { key, formName, props };
                    this.dlgs.push(dlg);
                }
                this.$nextTick(function () {
                    let ref = this.getRef(key);
                    if (ref.length) {
                        ref = ref[0];
                    }
                    resolve(ref);
                });
                return dlg;
            });
        },
        getRef(key) {
            return this.$refs['dlg' + key];
        },
        remove(key) {
            let dlg = this.dlgs.filter(p => p.key == key)[0];
            if (dlg) {
                let ix = this.dlgs.indexOf(dlg);
                if (ix > -1) {
                    this.dlgs.slice(ix, 1);
                }
            }
        },
        doClose(dlg) {
            if (dlg) {
                let ix = this.dlgs.indexOf(dlg);
                if (ix > -1) {
                    this.dlgs.splice(ix, 1);
                }
            }
        },
        open(formName, props, id, item) {
            let key = Date.now();
            return this.makeDlg(key, formName, props).then(dlg => {
                nextTick(()=>{
                    dlg.open(id, item);
                });
                return dlg;
            })
        },
        opendlg(tbname, id, item) {
            return this.open("my-form-dlg", { tbname }, id, item);
        },
        select(cfg, multi) {
            if (typeof (cfg) == "string") {
                cfg = { tbname: cfg };
            }

            return new Promise((resolve, reject) => {
                cfg = {
                    ...cfg,
                    onClear() {
                        resolve([]);
                    },
                    onSelected(items) {
                        items = toRaw(items);
                        resolve(items);
                    },
                    "onUpdate:modelValue"() {
                        if (arguments.length == 1) {
                            if(typeof(arguments[0])=="boolean" && arguments[0]==false)return;
                            resolve(arguments[0]);
                        } else {
                            let val = [];
                            for (let i = 0; i < arguments.length; i++) {
                                val.push(arguments[i])
                            }
                            resolve(val)
                        }
                    }
                };
                let key = Date.now();
                let selectWin = cfg.dlgName || ($mbh5 ? "MySelectWinH5" : "MySelectWin");

                delete cfg.dlgName;

                return this.makeDlg(key, selectWin, cfg).then(dlg => {
                    return dlg.open(multi == true);
                })
            })
        },
        showList(tbname, cfg) {
            cfg = { allowAdd: true, ...cfg, tbname: tbname, hideOK: true };
            let key = Date.now();
            let selectWin = cfg.dlgName ||  ($mbh5 ? "MySelectWinH5" : "MySelectWin");
            return this.makeDlg(key, selectWin, cfg).then(dlg => {
                return dlg.open(false);
            })
        },
        create(tbname, id, item, props) {
            id = id || 0;
            return new Promise((resolve, reject) => {
                let pm = {
                    ...props,
                    tbname,
                    onAdded(fmData) {
                        fmData = toRaw(fmData);
                        resolve(fmData)
                    },
                    onUpdated(fmData) {
                        fmData = toRaw(fmData);
                        resolve(fmData)
                    },
                    onDeleted(fmData) {
                        fmData = toRaw(fmData);
                        resolve({ _action: "delete", data: fmData });
                    },
                    onReload(fmData) {
                        fmData = toRaw(fmData);
                        resolve({ _action: "reload", data: fmData });
                    },
                };
                return this.open("my-form-dlg", pm, id, item);
            });
        },
        edit(tbname, id, item, formName, props) {
            return new Promise((resolve, reject) => {
                let pm = {
                    tbname,
                    formName,
                    onUpdated(fmData) {
                        fmData = toRaw(fmData);
                        resolve(fmData);
                    },
                    onAdded(fmData) {
                        fmData = toRaw(fmData);
                        resolve(fmData);
                    },
                    onDeleted(fmData) {
                        fmData = toRaw(fmData);
                        resolve({ _action: "delete", data: fmData });
                    },
                    onReload(fmData) {
                        fmData = toRaw(fmData);
                        resolve({ _action: "reload", data: fmData });
                    },
                    ...props,
                };
                return this.open("my-form-dlg", pm, id, item);
            });
        },
        view(tbname, id, item, formName, props) {
            let key = Date.now();
            return new Promise((resolve, reject) => {
                let pm = {
                    tbname,
                    formName,
                    onUpdated(fmData) {
                        fmData = toRaw(fmData);
                        resolve(fmData);
                    },
                    onAdded(fmData) {
                        fmData = toRaw(fmData);
                        resolve(fmData);
                    },
                    onDeleted(fmData) {
                        fmData = toRaw(fmData);
                        resolve({ _action: "delete", data: fmData });
                    },
                    onReload(fmData) {
                        fmData = toRaw(fmData);
                        resolve({ _action: "reload", data: fmData });
                    },
                    ...props,
                };
                return this.makeDlg(key, "my-form-dlg", pm).then(dlg => {
                    return dlg.view(id, item);
                })
            });
        },
        simpleEdit(tb, formData, readonly) {
            let key = Date.now();
            return this.makeDlg(key, "MySimpleFormDlg", {}).then(dlg => {
                if (readonly == true) {
                    return dlg.view(tb, formData);
                }
                return dlg.open(tb, formData);
            });
        },
        inputTextAndPhoto(title,  options) {
            let defaultContent = "";
            let photo = "";
            let needSign = false;
            let sign = "";
            if(options){
                switch(typeof options){
                    case "string":
                        defaultContent = options;
                        break;
                    case "object":
                        defaultContent = options.text || "";
                        photo = options.photo || "";
                        needSign = options.needSign;
                        sign = options.sign || "";
                        break;
                }
            }
            return new Promise((resolve, reject) => {
                let items = [
                    { TypeOf: 1, Content: defaultContent || "" },
                    { TypeOf: 2, Content: "", ImageList: photo.split(";") },
                ]
                let me = this;
                let cfg = {
                    modelValue: JSON.stringify(items),
                    title: title,
                    required: true,
                    disabled: false,
                    sign,
                    needSign,
                    multi: false,
                    "onUpdate:modelValue": (val) => {
                        let sign = "";
                        if(Array.isArray(val)){
                            sign = val[1];
                            val = val[0];
                        }
                        let itm2 = JSON.parse(val);
                        let content = itm2.find(p => p.TypeOf == 1).Content;
                        let photo = itm2.find(p => p.TypeOf == 2).ImageList.join(";");
                        let pm = {
                            content,
                            photo,
                            sign
                        }
                        resolve(pm);
                    }
                }
                this.open("TextAndImgEditDlg", cfg);
            });
        },

        editTextAndPhoto(title,text,photo,needSign){
            let opts = {
                text,
                photo,
                needSign,
                sign:""
            };
            return this.inputTextAndPhoto(title, opts);
        },

        editPhoto(title, photo, needSign, required) {
            if(required==undefined){
                required = true;
            }
            let cfg = {
                dlgName: "TextOrImgEditDlg",
                modelValue: photo,
                title: title,
                typeOf: "image",
                required: required,
                disabled: false,
                needSign,
            }
            //select方法，需要指定 tbname参数，或者专门的选择对话框名称  dlgName参数
            //对话框处理完成使用emit selected, clear, 或者 update:modelValue事件返回数据
            return $server.dlg.select(cfg);
        },

        editText(title, text, needSign, required) {
            if(required==undefined){
                required = true;
            }
            let cfg = {
                dlgName: "TextOrImgEditDlg",
                modelValue: text,
                title: title,
                typeOf: "text",
                required: required,
                disabled: false,
                needSign,
            }
            //select方法，需要指定 tbname参数，或者专门的选择对话框名称  dlgName参数
            //对话框处理完成使用emit selected, clear, 或者 update:modelValue事件返回数据
            return $server.dlg.select(cfg);
        },

        sign(sign){
            const signpm = {
                dlgName: "HandWriteDialog",
            }

            return $server.dlg.select(signpm)
        },

        selectTree(cfg){
            if(typeof(cfg)=="string"){
                cfg = {action:cfg};
            }
            cfg.dlgName = "MySelectTreeDlg"; 

            return $server.dlg.select(cfg);
        },

        showQrCode(qrcode,title){
            return $server.dlg.open("QrCodeDlg",{ title , qrcode });
        },

        viewImg(url){
            return $server.dlg.open("ViewImgDlg",{ url });
        }
    }

}
</script>